<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class SetController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function index(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'     => 'required|integer|min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        //处理
        $user_id  = $input["user_id"];

        //查找用户相关的通知集
        $teamAppId = env('TEAM_APP_ID');
        $teamSetId = env('TEAM_SET_ID');
        $setUserResult = DB::select("SELECT im_set_user.set_id,
            im_set_user.is_replied,im_set_user.is_viewed,im_set_user.is_latest,
            im_inform.id AS inform_id,im_inform.title AS inform_title,im_inform.send_time AS time,im_inform.is_closed,
            im_set.name AS set_name,im_set.icon AS set_icon
            FROM im_set_user
            INNER JOIN im_inform ON im_inform.id = im_set_user.inform_id
            INNER JOIN im_set ON im_set.id = im_set_user.set_id
            WHERE im_set_user.user_id = $user_id
            AND im_set.is_deleted = false
            ORDER BY im_set_user.created_at DESC 
            ");

        //聚合未回复数
        $setUserUnrepliedCount = [];
        foreach ($setUserResult as $value) {
            if($isInform)
                $count = ($value->is_replied || ($value->is_closed && $value->is_viewed))?0:1;
            else
                $count = $value->is_viewed?0:1;

            if(!isset($setUserUnrepliedCount[$value->set_id])){
                $setUserUnrepliedCount[$value->set_id] = $count;
            }else{
                $setUserUnrepliedCount[$value->set_id] += $count;
            }
        }

        //构造返回数据   
        $setUserReturn = [];
        foreach ($setUserResult as $value) {
            if($value->is_latest){
                unset($value->is_latest,$value->is_replied);
                $value->unreplied_count = $setUserUnrepliedCount[$value->set_id];
                $setUserReturn[] = $value;
            }
        }
        return $this::jsonResponse(false,$setUserReturn);
    }

    public function show($id)
    {

    }

    public function store(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'    => 'required|integer|min:1',
                'name'      => 'required|string|min:2',
                'icon'      => 'required|string|min:2',
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        //处理
        $appId    = $input["app_id"];
        $name     = $input["name"];
        $icon     = $input["icon"];

        $setData = [
            "app_id" => $appId,
            "name"   => $name,
            "icon"   => $icon
        ];

        $setId = DB::table("im_set")->insertGetId($setData);

        return $this::jsonResponse(false,$setId);
    }

    public function update(Request $request, $id)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'name'      => 'string|min:2',
                'icon'      => 'string|min:2',
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        //处理
        $setData = [];
        foreach (["name","icon"] as $value) {
            if(!empty($input[$value])) $setData[$value] = $input[$value];
        }
        
        if(empty($setData))
            return $this::jsonResponse(true,"","UpdateDataEmpty");

        $setUpdateResult = DB::table("im_set")->where("id",$id)->update($setData);

        return $this::jsonResponse(false,$setUpdateResult);
    }

    public function destroy($id)
    {
        DB::beginTransaction();

        DB::table("im_set")->where("id",$id)->update(["is_deleted"=>true]);
        DB::table("im_set_user")->where("set_id",$id)->delete();

        $informCloseData = [
            "is_closed"  =>true,
            "close_time" =>date("Y-m-d H:i:s")
        ];

        $informCloseResult = DB::table("im_inform")->where("set_id",$id)->update($informCloseData);
        
        DB::commit();

        return $this::jsonResponse(false,true);
    }

    public function destroyUser($setId,$userId)
    {
        $setUserResult = DB::table("im_set_user")->where("set_id",$setId)->where("user_id",$userId)->delete();

        return $this::jsonResponse(false,$setUserResult);
    }

}
